<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>课程管理系统</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .form-container {
            display: none;
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        .active-form {
            display: block;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,.3);
            border-radius: 50%;
            border-top-color: #007bff;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .pagination {
            margin: 20px 0;
            justify-content: center;
        }
        .page-item.active .page-link {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        .page-link {
            color: #0d6efd;
        }
        .page-item.disabled .page-link {
            color: #6c757d;
        }
        .search-container {
            margin-bottom: 20px;
        }
        .table-container {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>课程管理系统</h2>
        <button id="btnAddCourse" class="btn btn-primary">新增课程</button>
    </div>

    <div class="card search-container">
        <div class="card-body">
            <div class="input-group">
                <input type="text" id="searchCourseName" class="form-control" placeholder="输入课程名称">
                <button id="btnSearch" class="btn btn-primary">查询</button>
                <button id="btnReset" class="btn btn-outline-secondary">重置</button>
            </div>
        </div>
    </div>

    <div class="card table-container">
        <div class="card-body p-0">
            <div id="courseList">
                <table class="table table-striped table-hover mb-0">
                    <thead class="table-dark">
                    <tr>
                        <th>课程编号</th>
                        <th>课程名称</th>
                        <th>学分</th>
                        <th>授课教师</th>
                        <th>所属院系</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="courseListBody">
                    <!-- 动态填充内容 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <nav aria-label="Page navigation">
        <ul class="pagination" id="pagination">
            <!-- 分页按钮将通过JS动态生成 -->
        </ul>
    </nav>

    <div id="courseForm" class="form-container">
        <h3 id="formTitle">新增课程</h3>
        <form id="courseFormElement" method="post">
            <input type="hidden" id="formType" name="_method" value="post">
            <input type="hidden" id="courseId" name="courseNo">

            <div class="mb-3">
                <label for="courseNo" class="form-label">课程编号</label>
                <input type="number" class="form-control" id="courseNo" name="courseNo" required>
            </div>

            <div class="mb-3">
                <label for="courseName" class="form-label">课程名称</label>
                <input type="text" class="form-control" id="courseName" name="courseName" required>
            </div>

            <div class="mb-3">
                <label for="credit" class="form-label">学分</label>
                <input type="text" class="form-control" id="credit" name="credit" required>
            </div>

            <div class="mb-3">
                <label for="teacherNo" class="form-label">授课教师</label>
                <div class="input-group">
                    <select class="form-select" id="teacherNo" name="teacherNo" required>
                        <option value="">-- 请选择教师 --</option>
                    </select>
                    <button type="button" id="btnLoadTeachers" class="btn btn-outline-secondary">
                        <span id="teacherLoading" class="loading" style="display:none;"></span>
                        加载教师
                    </button>
                </div>
            </div>

            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" id="submitBtn" class="btn btn-primary me-md-2">保存</button>
                <button type="button" id="btnCancel" class="btn btn-secondary">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
    $(document).ready(function() {
        // 状态管理
        const state = {
            currentPage: 1,
            pageSize: 10,
            totalPages: 1,
            totalRecords: 0,
            currentSearch: '',
            allTeachers: [],
            teachersLoaded: false,
            originalCourseData: null
        };

        // 初始化加载 - 先加载教师数据，再加载课程列表
        function initialize() {
            loadTeachers().done(function() {
                state.teachersLoaded = true;
                loadCourseList();
            }).fail(function(error) {
                console.error('教师数据加载失败:', error);
                // 即使教师加载失败，也加载课程列表
                loadCourseList();
            });
        }

        initialize();

        // 事件绑定
        $('#btnSearch').click(function() {
            state.currentSearch = $('#searchCourseName').val().trim();
            state.currentPage = 1;
            loadCourseList();
        });

        $('#btnReset').click(function() {
            $('#searchCourseName').val('');
            state.currentSearch = '';
            state.currentPage = 1;
            loadCourseList();
        });

        $('#btnAddCourse').click(function() {
            showForm('新增课程', 'post');
            resetForm();
            if (!state.teachersLoaded) {
                loadTeachers();
            }
        });

        $('#btnLoadTeachers').click(loadTeachers);
        $('#btnCancel').click(hideForm);

        // 编辑/删除按钮事件委托
        $(document).on('click', '.btn-edit', function() {
            const courseNo = $(this).data('id');
            showForm('编辑课程', 'put');
            loadCourseData(courseNo);
        });

        $(document).on('click', '.btn-delete', function() {
            const courseNo = $(this).data('id');
            if (confirm('确定要删除此课程吗？')) {
                deleteCourse(courseNo);
            }
        });

        // 表单提交处理
        $('#courseFormElement').submit(function(e) {
            e.preventDefault();
            handleFormSubmit();
            return false;
        });

        // 加载课程列表
        function loadCourseList() {
            let url = `/courses/getAll?current=${state.currentPage}&size=${state.pageSize}`;
            if (state.currentSearch) {
                url += `&courseName=${encodeURIComponent(state.currentSearch)}`;
            }

            $.ajax({
                url: url,
                type: 'GET',
                success: function(data) {
                    if (data.code === '200') {
                        renderCourseList(data.data.list);
                        state.totalRecords = data.data.total;
                        state.totalPages = data.data.pages;
                        renderPagination();
                    } else {
                        alert(data.msg || '获取数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载课程列表失败:', error);
                    alert('加载失败: ' + (xhr.responseJSON && xhr.responseJSON.msg || error));
                }
            });
        }

        // 渲染课程列表 - 修改后的核心函数
        function renderCourseList(courses) {
            const $courseListBody = $('#courseListBody');
            $courseListBody.empty();

            if (!courses || !Array.isArray(courses)) {
                $courseListBody.html(`
                <tr>
                    <td colspan="6" class="text-center py-4">
                        课程数据格式错误
                    </td>
                </tr>
            `);
                return;
            }

            if (courses.length === 0) {
                $courseListBody.html(`
                <tr>
                    <td colspan="6" class="text-center py-4">
                        ${state.currentSearch ? '没有找到匹配的课程' : '暂无课程数据'}
                    </td>
                </tr>
            `);
                return;
            }

            // 如果教师数据未加载，先显示基本课程信息并加载教师数据
            if (!state.teachersLoaded) {
                courses.forEach(course => {
                    $courseListBody.append(`
                    <tr>
                        <td>${course.courseNo}</td>
                        <td>${course.courseName}</td>
                        <td>${course.credit}</td>
                        <td class="teacher-info">加载中...</td>
                        <td class="department-info">加载中...</td>
                        <td class="text-nowrap">
                            <button data-id="${course.courseNo}" class="btn-edit btn btn-sm btn-outline-primary me-1">编辑</button>
                            <button data-id="${course.courseNo}" class="btn-delete btn btn-sm btn-outline-danger">删除</button>
                        </td>
                    </tr>
                `);
                });

                // 异步加载教师数据
                loadTeachers().done(function() {
                    // 教师数据加载完成后，更新教师和院系信息
                    updateTeacherInfo();
                });
                return;
            }

            // 教师数据已加载，正常渲染
            courses.forEach(course => {
                const teacher = state.allTeachers.find(t => t.teacherNo === course.teacherNo) || {};
                $courseListBody.append(`
                <tr>
                    <td>${course.courseNo}</td>
                    <td>${course.courseName}</td>
                    <td>${course.credit}</td>
                    <td>${teacher.name || '-'}</td>
                    <td>${teacher.department || '-'}</td>
                    <td class="text-nowrap">
                        <button data-id="${course.courseNo}" class="btn-edit btn btn-sm btn-outline-primary me-1">编辑</button>
                        <button data-id="${course.courseNo}" class="btn-delete btn btn-sm btn-outline-danger">删除</button>
                    </td>
                </tr>
            `);
            });
        }

        // 更新教师信息 - 新增函数
        function updateTeacherInfo() {
            $('#courseListBody tr').each(function() {
                const courseNo = parseInt($(this).find('td:first').text());
                const course = state.courses?.find(c => c.courseNo === courseNo);
                if (course) {
                    const teacher = state.allTeachers.find(t => t.teacherNo === course.teacherNo) || {};
                    $(this).find('.teacher-info').text(teacher.name || '-');
                    $(this).find('.department-info').text(teacher.department || '-');
                }
            });
        }

        // 渲染分页
        function renderPagination() {
            const $pagination = $('#pagination');
            $pagination.empty();

            // 上一页按钮
            const prevDisabled = state.currentPage === 1 ? 'disabled' : '';
            $pagination.append(`
            <li class="page-item ${prevDisabled}">
                <a class="page-link" href="#" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        `);

            // 页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, state.currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(state.totalPages, startPage + maxVisiblePages - 1);

            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            // 第一页按钮
            if (startPage > 1) {
                $pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="#">1</a>
                </li>
            `);

                if (startPage > 2) {
                    $pagination.append(`
                    <li class="page-item disabled">
                        <span class="page-link">...</span>
                    </li>
                `);
                }
            }

            // 中间页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const active = i === state.currentPage ? 'active' : '';
                $pagination.append(`
                <li class="page-item ${active}">
                    <a class="page-link" href="#">${i}</a>
                </li>
            `);
            }

            // 最后一页按钮
            if (endPage < state.totalPages) {
                if (endPage < state.totalPages - 1) {
                    $pagination.append(`
                    <li class="page-item disabled">
                        <span class="page-link">...</span>
                    </li>
                `);
                }

                $pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="#">${state.totalPages}</a>
                </li>
            `);
            }

            // 下一页按钮
            const nextDisabled = state.currentPage === state.totalPages ? 'disabled' : '';
            $pagination.append(`
            <li class="page-item ${nextDisabled}">
                <a class="page-link" href="#" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        `);

            // 绑定分页点击事件
            $pagination.find('.page-link').click(function(e) {
                e.preventDefault();
                const $li = $(this).closest('li');
                if ($li.hasClass('disabled')) return;

                const text = $(this).text().trim();
                if (text === '«') {
                    state.currentPage--;
                } else if (text === '»') {
                    state.currentPage++;
                } else if (text === '...') {
                    return;
                } else {
                    state.currentPage = parseInt(text);
                }
                loadCourseList();
            });
        }

        // 加载课程数据
        function loadCourseData(courseNo) {
            $.ajax({
                url: `/courses/${courseNo}`,
                type: 'GET',
                success: function(data) {
                    if (data.code !== '200') {
                        throw new Error(data.msg);
                    }

                    const course = data.data;
                    state.originalCourseData = {
                        courseNo: course.courseNo,
                        courseName: course.courseName,
                        credit: course.credit,
                        teacherNo: course.teacherNo
                    };

                    $('#courseId').val(course.courseNo);
                    $('#courseNo').val(course.courseNo);
                    $('#courseName').val(course.courseName);
                    $('#credit').val(course.credit);

                    loadTeachers().done(function() {
                        $('#teacherNo').val(course.teacherNo || '');
                        $('#courseNo').prop('readonly', true);
                    });
                },
                error: function(xhr, status, error) {
                    console.error('加载课程数据失败:', error);
                    alert('加载课程数据失败: ' + (xhr.responseJSON && xhr.responseJSON.msg || error));
                    hideForm();
                }
            });
        }

        // 加载教师数据
        function loadTeachers() {
            $('#teacherLoading').show();
            $('#btnLoadTeachers').prop('disabled', true);

            return $.ajax({
                url: '/teacher/getAll?current=1&size=1000',
                type: 'GET',
                success: function(data) {
                    if (data.code === '200' && Array.isArray(data.data.list)) {
                        state.allTeachers = data.data.list;
                        updateTeacherSelect(state.allTeachers);
                        state.teachersLoaded = true;

                        // 如果课程列表已显示，更新教师信息
                        if ($('#courseListBody tr').length > 0) {
                            updateTeacherInfo();
                        }
                    } else {
                        throw new Error(data.msg || '教师数据格式不正确');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载教师失败:', error);
                    $('#teacherNo').html('<option value="">-- 加载教师失败，请重试 --</option>');
                    throw error;
                },
                complete: function() {
                    $('#teacherLoading').hide();
                    $('#btnLoadTeachers').prop('disabled', false);
                }
            });
        }

        // 更新教师下拉框
        function updateTeacherSelect(teachers) {
            if (!Array.isArray(teachers)) {
                console.error('updateTeacherSelect: teachers不是数组', teachers);
                teachers = [];
            }

            let options = '<option value="">-- 请选择教师 --</option>';
            teachers.forEach(teacher => {
                if (teacher && teacher.teacherNo) {
                    options += `<option value="${teacher.teacherNo}">${teacher.name || '未知'} (${teacher.department || '无院系'})</option>`;
                }
            });
            $('#teacherNo').html(options);
        }

        // 删除课程
        function deleteCourse(courseNo) {
            $.ajax({
                url: `/courses/${courseNo}`,
                type: 'DELETE',
                success: function(data) {
                    if (data.code === '200') {
                        alert('删除成功');
                        loadCourseList();
                    } else {
                        alert(data.msg || '删除失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('删除失败:', error);
                    alert('删除失败: ' + (xhr.responseJSON && xhr.responseJSON.msg || error));
                }
            });
        }

        // 表单提交处理
        function handleFormSubmit() {
            const $submitBtn = $('#submitBtn');
            const originalText = $submitBtn.html();

            if (!validateForm()) {
                return false;
            }

            const isEdit = $('#formType').val() === 'put';
            const formData = prepareFormData(isEdit);

            $submitBtn.prop('disabled', true);
            $submitBtn.html('<span class="loading"></span> 提交中...');

            const url = isEdit ? `/courses/${state.originalCourseData.courseNo}` : '/courses';
            const method = isEdit ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(data) {
                    if (data.code === '200') {
                        alert(isEdit ? '课程更新成功' : '课程添加成功');
                        loadCourseList();
                        hideForm();
                    } else {
                        alert(data.msg || '操作失败');
                    }
                },
                error: function(xhr, status, error) {
                    let errorMessage = error;
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMessage = xhr.responseJSON.msg;
                    }
                    alert(`操作失败: ${errorMessage}`);
                },
                complete: function() {
                    $submitBtn.prop('disabled', false);
                    $submitBtn.html(originalText);
                }
            });
        }

        // 准备表单数据
        function prepareFormData(isEditMode) {
            const courseNo = isEditMode ?
                state.originalCourseData.courseNo :
                parseInt($('#courseNo').val());

            return {
                courseNo: courseNo,
                courseName: $('#courseName').val().trim(),
                credit: $('#credit').val().trim(),
                teacherNo: $('#teacherNo').val() ? parseInt($('#teacherNo').val()) : null
            };
        }

        // 显示表单
        function showForm(title, method) {
            $('#formTitle').text(title);
            $('#formType').val(method);
            $('#courseForm').addClass('active-form');
            $('#btnAddCourse').hide();
        }

        // 隐藏表单
        function hideForm() {
            $('#courseForm').removeClass('active-form');
            $('#btnAddCourse').show();
            $('#courseNo').prop('readonly', false);
            state.originalCourseData = null;
        }

        // 重置表单
        function resetForm() {
            $('#courseFormElement')[0].reset();
            if (state.teachersLoaded) {
                updateTeacherSelect(state.allTeachers);
            } else {
                $('#teacherNo').html('<option value="">-- 请先点击加载教师数据 --</option>');
            }
            state.originalCourseData = null;
        }

        // 验证表单
        function validateForm() {
            if (!$('#courseNo').val() || !$('#courseName').val() || !$('#credit').val()) {
                alert("请填写完整的课程信息");
                return false;
            }
            return true;
        }
    });
</script>
</body>
</html>